/*
 * Storage 存储封装
 * @author Leriy
*/
import config from '@/config/index'

export function getNameSpaceStorage() {
    return JSON.parse(window.localStorage.getItem(config.storageNamespace) || '{}')
}

/*
 * @desc 设置 localStorage
 * @param {String} key - 属性名
 * @param {Any} val - 值
*/
export function setLocal(key, val) {
    let storage = getNameSpaceStorage()
    storage[key] = val
    window.localStorage.setItem(config.storageNamespace, JSON.stringify(storage))
}

/*
 * @desc 获取 localStorage
 * @param {String} key - 属性名
*/
export function getLocal(key) {
    return getNameSpaceStorage()[key]
}

/*
 * @desc 删除 localStorage
 * @param {String} key - 属性名
*/
export function clearLocal(key) {
    let storage = getNameSpaceStorage()
    delete storage[key]
    window.localStorage.setItem(config.storageNamespace, JSON.stringify(storage))
}


/*
 * @desc 删除所有localStorage
 * @param {Array} except - 删除except以外的属性   
*/
export function clearAllLocal(except = []) {
    const localKeys = Object.keys(localStorage)
    localKeys.forEach((item) => {
        if (!(except.includes(item))) localStorage.removeItem(item);
    })
}

/*
 * @desc 设置 Cookie
 * @param {String} key - 属性名 
 * @param {Any} value - 值
 * @param {Number} days - 天数,如果不指定过期时间，则默认为浏览器会话结束时过期
*/
export function setCookie(key, value, days) {
    let expires = '';
    if (days) {
        const date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = `; expires=${date.toGMTString()}`;
    }
    document.cookie = `${key}=${value}${expires}; path=/`;
}

/*
 * @desc 获取 Cookie
 * @param {String} key - 属性名 
*/
export function getCookie(key) {
    const nameEQ = `${key}=`;
    const ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
}

/*
 * @desc 删除 Cookie
 * @param {String} key - 属性名 
*/
export function deleteCookie(key) {
    document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
}

/*
 * @desc 删除所有 Cookie
*/
export function clearAllCookie() {
    const allCookies = document.cookie.match(/[^ =;]+(?=\=)/g)
    allCookies.forEach((item) => {
        deleteCookie(item)
    })
}